package com.soujiayi.activity;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.soujiayi.model.Mall;
import com.soujiayi.model.Product;
import com.soujiayi.model.SkimHistory;
import com.soujiayi.net.HttpRequester;
import com.soujiayi.net.ImageLoader;
import com.soujiayi.net.NetworkUtils;
import com.soujiayi.share.WeixinAPI;
import com.soujiayi.store.DatabaseManager;
import com.soujiayi.util.CommonUtils;
import com.soujiayi.util.Constants;
import com.soujiayi.util.UserKeeper;
import com.soujiayi.weibo.User;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ProductDetailActivity extends Activity {

	private Product product;
	private Mall mall;
	private Mall lowestPriceMall;
	private String price;
	private String mallName;
	private ImageLoader imageLoader;
	private List<String> mallsupport;
	private int mallnum;
	private boolean isParity = false;
	private boolean isLowestPrice = false;
	private DatabaseManager databaseManager = new DatabaseManager(
			ProductDetailActivity.this);
	private AdView adView;
	private String imageUrl = "";
	private String shareImgUrl = "";
	private Button btn_product_favorite;
	private HttpRequester httpRequester;
	private ProgressDialog progressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		((MyApplication) this.getApplication()).addActivity(this);
		setContentView(R.layout.product_detail);

		Intent intent = this.getIntent();
		isParity = intent.getBooleanExtra(Constants.PRODUCT_IS_PARITY, false);
		isLowestPrice = intent.getBooleanExtra("isLowestPrice", false);
		product = (Product) intent.getSerializableExtra(Constants.PRODUCT);
		if (isParity) {
			mall = (Mall) intent
					.getSerializableExtra(Constants.PRODUCT_COMPARE_MALL);
			price = String.valueOf(mall.getPrice());
			mallName = mall.getMallname();
			mallnum = product.getCompare().getMallnum();
		} else {
			price = product.getSaleprice();
			mallName = product.getMallname();
		}
		mallsupport = product.getMallsupport();
		initMallSupport();

		progressDialog = new ProgressDialog(ProductDetailActivity.this);
		progressDialog.setMessage(getResources().getString(
				R.string.submit_loading));
		progressDialog.setCancelable(false);
		Window window = progressDialog.getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		lp.alpha = 0.7f;// 透明度
		lp.dimAmount = 0.5f;// 黑暗度
		window.setAttributes(lp);

		TextView productDescription = (TextView) findViewById(R.id.product_detail_description);
		productDescription.setText(product.getName());

		btn_product_favorite = (Button) this
				.findViewById(R.id.btn_product_favorite);

		// Download product image
		imageLoader = new ImageLoader(this, true, 200, 200, 1);
		ImageView productImage = (ImageView) findViewById(R.id.product_detail_Img);
		if (product.getCover() != null) {
			imageUrl = product.getCover().replace(".jpg", ".200x200.jpg");
			shareImgUrl = product.getCover();
			imageLoader.DisplayImage(imageUrl, productImage);
		}

		TextView productPrice = (TextView) findViewById(R.id.product_detail_price);
		String price_unit = this.getResources().getString(R.string.price_unit);
		productPrice.setText(price + price_unit);

		TextView productMall = (TextView) findViewById(R.id.product_detail_mall);
		productMall.append(": " + mallName);

		TextView productMallDescription = (TextView) findViewById(R.id.product_detail_mall_description);
		productMallDescription
				.setText("华强商城（深圳华强商城股份有限公司）隶属华强集团旗下，是目前中国领先的网上购物平台。");
		productMallDescription.setVisibility(View.GONE);

		adView = (AdView) this.findViewById(R.id.av_productdetail_ad);
		Map<String, Object> extras = new HashMap<String, Object>();
		extras.put("color_bg", "5f970e");
		extras.put("color_bg_top", "5f970e");
		extras.put("color_border", "FFFFFF");
		extras.put("color_link", "FFFFFF");
		extras.put("color_text", "FFFFFF");
		extras.put("color_url", "0066CC");

		AdRequest adRequest = new AdRequest();
		adRequest.setExtras(extras);
		adView.loadAd(adRequest);

		insertSkimHistory();

		RelativeLayout lowestLayout = (RelativeLayout) findViewById(R.id.product_detail_lowest_layout);
		lowestLayout.setVisibility(View.GONE);
		if (isParity && !isLowestPrice && mallnum >= 1) {
			List<Mall> malls = product.getCompare().getMalls();
			Collections.sort(malls, new Comparator<Mall>() {
				@Override
				public int compare(Mall o1, Mall o2) {
					return o1.getPrice() > o2.getPrice() ? 1
							: (o1.getPrice() == o2.getPrice() ? 0 : -1);
				}
			});
			lowestPriceMall = malls.get(0);
			if (lowestPriceMall.getPrice() == mall.getPrice()) {
				lowestLayout.setVisibility(View.GONE);
				return;
			} else {

				lowestLayout.setVisibility(View.VISIBLE);
				TextView productLowestDescription = (TextView) findViewById(R.id.product_detail_lowest_description);
				productLowestDescription.setText(String.valueOf(mallnum)
						+ productLowestDescription.getText());

				TextView productLowestPrice = (TextView) findViewById(R.id.product_detail_lowest_price);
				productLowestPrice.setText(String.valueOf(lowestPriceMall
						.getPrice()));
				lowestLayout.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(ProductDetailActivity.this,
								ProductDetailActivity.class);
						intent.putExtra(Constants.PRODUCT_IS_PARITY, true);
						intent.putExtra("isLowestPrice", true);
						intent.putExtra(Constants.PRODUCT_COMPARE_MALL,
								lowestPriceMall);
						intent.putExtra(Constants.PRODUCT, product);
						startActivity(intent);
						overridePendingTransition(R.anim.push_left_in,
								R.anim.push_left_out);
					}
				});
			}
		}

		User user = UserKeeper.readUser(ProductDetailActivity.this,
				Constants.PREFERENCES_NAME_USER);
		if (user != null && !CommonUtils.isEmpty(user.getUsername())) {
			if (databaseManager.isFavoriteExist("goods", product.getGoodsid())) {
				btn_product_favorite.setBackgroundDrawable(this.getResources()
						.getDrawable(R.drawable.menu_favorite_on));
			}
		}

		Handler favoriteHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				progressDialog.dismiss();
				if (msg.what == 1) {
					if (msg.arg1 == 1) {
						databaseManager.insertFavorite("goods",
								product.getGoodsid(), "");
						btn_product_favorite
								.setBackgroundDrawable(ProductDetailActivity.this
										.getResources().getDrawable(
												R.drawable.menu_favorite_on));
						Toast.makeText(
								ProductDetailActivity.this,
								ProductDetailActivity.this
										.getString(R.string.product_favorite_success),
								Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(
								ProductDetailActivity.this,
								ProductDetailActivity.this
										.getString(R.string.product_favorite_fail),
								Toast.LENGTH_SHORT).show();
					}
				} else if (msg.what == 2) {
					if (msg.arg1 == 1) {
						databaseManager.deleteFavorite("goods",
								product.getGoodsid());
						btn_product_favorite
								.setBackgroundDrawable(ProductDetailActivity.this
										.getResources().getDrawable(
												R.drawable.menu_favorite_off));
						Toast.makeText(
								ProductDetailActivity.this,
								ProductDetailActivity.this
										.getString(R.string.cancel_favorite_success),
								Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(
								ProductDetailActivity.this,
								ProductDetailActivity.this
										.getString(R.string.cancel_favorite_fail),
								Toast.LENGTH_SHORT).show();
					}
				}
			}

		};
		httpRequester = new HttpRequester(this, 1, favoriteHandler);

	}

	public void initMallSupport() {
		if (mallsupport != null && mallsupport.size() > 0 && !isLowestPrice) {
			String keywords = "";
			if (mallsupport.contains("1")) {
				keywords += ProductDetailActivity.this.getResources()
						.getString(R.string.product_detail_mallsupport_1) + " ";
			}
			if (mallsupport.contains("2")) {
				keywords += ProductDetailActivity.this.getResources()
						.getString(R.string.product_detail_mallsupport_2) + " ";
			}
			if (mallsupport.contains("3")) {
				keywords += ProductDetailActivity.this.getResources()
						.getString(R.string.product_detail_mallsupport_3) + " ";
			}
			if (mallsupport.contains("4")) {
				keywords += ProductDetailActivity.this.getResources()
						.getString(R.string.product_detail_mallsupport_4);
			}
			TextView productMallKeyword = (TextView) findViewById(R.id.product_detail_mall_keyword);
			productMallKeyword.setText(keywords);
		}
	}

	public void backToHome(View view) {
		Intent intent = new Intent(ProductDetailActivity.this,
				IndexActivity.class);
		startActivity(intent);
		this.finish();
	}

	public void back(View view) {
		this.finish();
		overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
	}

	public void look(View view) {
		Intent intent = new Intent(ProductDetailActivity.this,
				ProductDetailWebViewActivity.class);
		if (isParity) {
			intent.putExtra(Constants.PRODUCT_URL, mall.getBuyurl());
		} else {
			intent.putExtra(Constants.PRODUCT_URL, product.getBuyurl());
		}
		intent.putExtra(Constants.PRODUCT_NAME, product.getName());
		startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	public void gotoComment(View view) {
		Intent intent = new Intent(ProductDetailActivity.this,
				ProductCommentActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	public void favorite(View view) {
		if (!NetworkUtils.isNetworkConnected(ProductDetailActivity.this)) {
			Toast.makeText(
					ProductDetailActivity.this,
					ProductDetailActivity.this
							.getString(R.string.network_unavailable_message),
					Toast.LENGTH_LONG).show();
			return;
		}

		User user = databaseManager.getOnlineUser();
		if (user == null || CommonUtils.isEmpty(user.getUsername())) {
			Intent intent = new Intent(ProductDetailActivity.this,
					SoujiayiLoginActivity.class);
			intent.putExtra(Constants.IS_NOT_FROM_SETTING, true);
			startActivity(intent);
		} else {
			HashMap<String, String> parameters = new HashMap<String, String>();
			parameters.put("sid",
					((MyApplication) this.getApplication()).getSessionId());
			parameters.put("type", "goods");
			parameters.put("autoid", product.getGoodsid());
			progressDialog.show();
			if (!databaseManager.isFavoriteExist("goods", product.getGoodsid())) {
				httpRequester.addFavorite(parameters);
			} else {
				httpRequester.delFavorite(parameters);
			}
		}
	}

	public void share(View view) {
		final CharSequence[] items = {
				getResources().getString(R.string.share_sms),
				getResources().getString(R.string.share_email),
				getResources().getString(R.string.share_weixin_friends),
				getResources().getString(R.string.share_weixin_friend_group),
				getResources().getString(R.string.share_weibo) };

		final String shareMailSubject = getResources().getString(
				R.string.share_send_product_email_subject);
		AlertDialog.Builder builder = new AlertDialog.Builder(
				ProductDetailActivity.this);
		builder.setTitle(getResources().getString(R.string.share_to)).setItems(
				items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						String priceUnit = ProductDetailActivity.this
								.getResources().getString(R.string.price_unit);
						String shareContent = "";
						String url = "";
						if (mall != null) {
							shareContent = mall.getMallname() + ":"
									+ product.getName() + " " + mall.getPrice()
									+ priceUnit;
							url = mall.getBuyurl();
							if (shareContent.length() > 95) {
								int len = shareContent.length() - 95;
								shareContent = mall.getMallname()
										+ ":"
										+ product.getName().substring(
												0,
												product.getName().length()
														- len) + " "
										+ mall.getPrice() + priceUnit;
							}
						} else {
							shareContent = product.getMallname() + ":"
									+ product.getName() + " "
									+ product.getSaleprice() + priceUnit;
							url = product.getBuyurl();
							if (shareContent.length() > 95) {
								int len = shareContent.length() - 95;
								shareContent = product.getMallname()
										+ ":"
										+ product.getName().substring(
												0,
												product.getName().length()
														- len) + " "
										+ product.getPrice() + priceUnit;
							}
						}
						switch (item) {
						case 0:
							shareContent = shareContent + " " + url;
							Uri uri = Uri.parse("smsto:");
							Intent smsIt = new Intent(Intent.ACTION_SENDTO, uri);
							smsIt.putExtra("sms_body", shareContent);
							ProductDetailActivity.this.startActivity(smsIt);
							break;
						case 1:
							shareContent = shareContent + " " + url;
							Uri mallto = Uri.parse("mailto:");

							Intent mailIt = new Intent(Intent.ACTION_SENDTO,
									mallto);
							mailIt.putExtra(Intent.EXTRA_SUBJECT,
									shareMailSubject);
							mailIt.putExtra(Intent.EXTRA_TEXT, shareContent);
							try {
								ProductDetailActivity.this
										.startActivity(mailIt);
							} catch (Exception e) {
								Toast.makeText(
										ProductDetailActivity.this,
										ProductDetailActivity.this
												.getString(R.string.share_to_mailbox_failed),
										Toast.LENGTH_LONG).show();
							}
							break;
						case 2:
							if (CommonUtils.isAppInstalled(
									ProductDetailActivity.this,
									"com.tencent.mm")) {
								WeixinAPI api = new WeixinAPI(
										ProductDetailActivity.this);
								api.shareToWeixin(product.getName(),
										shareContent, imageUrl, url, 1);
							} else {
								AlertDialog.Builder builder = new Builder(
										ProductDetailActivity.this);
								builder.setTitle(ProductDetailActivity.this
										.getString(R.string.weixin_download_title));
								builder.setMessage(ProductDetailActivity.this
										.getString(R.string.weixin_download_message));

								builder.setPositiveButton(
										ProductDetailActivity.this
												.getString(R.string.confirm),
										new DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												dialog.dismiss();
												Uri uri = Uri
														.parse("http://weixin.qq.com/m");
												Intent it = new Intent(
														Intent.ACTION_VIEW, uri);
												startActivity(it);
											}
										});

								builder.setNegativeButton(
										ProductDetailActivity.this
												.getString(R.string.cancel),
										new DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												dialog.dismiss();
											}
										});
								Dialog noticeDialog = builder.create();
								noticeDialog.show();
							}
							break;
						case 3:
							if (CommonUtils.isAppInstalled(
									ProductDetailActivity.this,
									"com.tencent.mm")) {
								WeixinAPI api = new WeixinAPI(
										ProductDetailActivity.this);
								api.shareToWeixin(product.getName(),
										shareContent, imageUrl, url, 2);
							} else {
								AlertDialog.Builder builder = new Builder(
										ProductDetailActivity.this);
								builder.setTitle(ProductDetailActivity.this
										.getString(R.string.weixin_download_title));
								builder.setMessage(ProductDetailActivity.this
										.getString(R.string.weixin_download_message));

								builder.setPositiveButton(
										ProductDetailActivity.this
												.getString(R.string.confirm),
										new DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												dialog.dismiss();
												Uri uri = Uri
														.parse("http://weixin.qq.com/m");
												Intent it = new Intent(
														Intent.ACTION_VIEW, uri);
												startActivity(it);
											}
										});

								builder.setNegativeButton(
										ProductDetailActivity.this
												.getString(R.string.cancel),
										new DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												dialog.dismiss();
											}
										});
								Dialog noticeDialog = builder.create();
								noticeDialog.show();
							}
							break;
						case 4:
							shareContent = shareContent + " " + url;
							Intent intent = new Intent(
									ProductDetailActivity.this,
									ShareActivity.class);
							intent.putExtra(Constants.IS_NOT_FROM_SETTING, true);
							intent.putExtra("shareContent", shareContent);
							intent.putExtra("imageUrl", shareImgUrl);
							startActivity(intent);
							overridePendingTransition(R.anim.push_up_in,
									R.anim.push_up_out);
							break;
						default:
							break;
						}
					}
				});
		Dialog dialog = builder.create();
		dialog.show();
	}

	public void insertSkimHistory() {
		if (!isParity) {
			SkimHistory skimHistory = new SkimHistory();
			skimHistory.setType(Constants.SKIM_HISTORY_TYPE_PRODUCT);
			skimHistory.setName(product.getName());
			skimHistory.setCover(product.getCover());
			skimHistory.setGoodsid(product.getGoodsid());
			skimHistory.setSaleprice(product.getSaleprice());
			skimHistory.setMallid(product.getMallid());
			skimHistory.setMallname(product.getMallname());
			skimHistory.setMallCount("0");
			databaseManager.insertSKimHistory(skimHistory);
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 如果按下的是返回键，并且没有重复
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			overridePendingTransition(R.anim.push_right_in,
					R.anim.push_right_out);
			return false;
		}
		return false;
	}

	@Override
	protected void onDestroy() {
		if (adView != null) {
			adView.destroy();
		}
		imageLoader.close();
		databaseManager.closeDB();
		super.onDestroy();
	}

}
